package com.gengao.springbootcase.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Component
@AllArgsConstructor
@NoArgsConstructor
@Data
public class AliOSSUtils  {
    private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    private String bucketName = "javaweb-aliyunoss-gengao";


    public String uploadFile(MultipartFile multipartFile) throws Exception {
//        String result = null;
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        InputStream inputStream = multipartFile.getInputStream();
        String originalFileName = multipartFile.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFileName.substring(originalFileName.lastIndexOf("."));
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
//        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        ossClient.putObject(putObjectRequest);
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
        String url=ossClient.generatePresignedUrl(bucketName,fileName,expiration).toString();
        ossClient.shutdown();
        return url;
    }
}




